package com.tangzx.builder.decoder;

import java.util.Iterator;
import java.util.Set;

import com.tangzx.builder.SwfMovie;
import com.tangzx.builder.abc.AbcFile;
import com.tangzx.builder.context.AbcContext;
import com.tangzx.builder.context.IAbcContext;
import flash.swf.MovieDecoder;
import flash.swf.tags.DoABC;
import flash.swf.tags.SymbolClass;

public class MovieABCDecoder extends MovieDecoder {

	protected IAbcContext abcContext;
	protected SwfMovie sm;

	public MovieABCDecoder(SwfMovie m) {
		this(m, new AbcContext());
	}

	public MovieABCDecoder(SwfMovie m, IAbcContext context) {
		super(m);
		sm = m;
		abcContext = context;
	}

	private void setNSQ(String key) {
		int last = key.lastIndexOf(".");
		String qn = key;
		if (last != -1) {
			String ns = key.substring(0, last);
			qn = key.substring(last + 1);
			abcContext.getString(ns).vo.pushString(true);
		}
		abcContext.getString(qn).vo.pushString(true);
		//System.out.println("##############" + key);
	}

	@Override
	public void symbolClass(SymbolClass tag) {
		super.symbolClass(tag);
		if (tag.topLevelClass != null)
			setNSQ(tag.topLevelClass);
		Set<String> keySet = tag.class2tag.keySet();
		for (Iterator<String> it = keySet.iterator(); it.hasNext();) {
			String key = (String) it.next();
			setNSQ(key);
		}
	}

	public IABCDecoder getABCDecoder() {
		return new AbcDecoder();
	}

	@Override
	public void doABC(DoABC tag) {
		super.doABC(tag);
		IABCDecoder ad = getABCDecoder();
		ad.setAbcContext(abcContext);
		AbcFile file = ad.readAbc(tag);
		sm.abcs.add(file);
	}

	public IAbcContext getAbcContext() {
		return abcContext;
	}
}